package com.bluefox.aspect;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * 日志切面
 */
@Slf4j
@Configuration
@Aspect
public class WebLogAspectAutoConfiguration {

    //@Pointcut("execution(* com.bluefox..*.*(..)) && @target(org.springframework.web.bind.annotation.RestController)")
    public void executeHandler() {
    }

    //@Around("executeHandler()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

        Object[] args = pjp.getArgs();
        Optional<Object> httpObject = Stream.of(args).filter(o -> o instanceof HttpServletRequest || o instanceof HttpServletResponse).findFirst();
        if (httpObject.isPresent()) {
            return pjp.proceed();
        }

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String uri = request.getRequestURI();
        try {
            log.info("request log --> uri: " + uri + "  args:" + JSONObject.toJSONString(pjp.getArgs()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Object result = pjp.proceed();
       log.info("request log --> return: " + JSONObject.toJSONString(result));
        return result;
    }
}
